package org.zjt.helloworld;

import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;
import org.zjt.helloworld.domain.RequestMsgProto;

/**
 * Created by zhangjuntao on 2017/3/16.
 */
public class SubReqClientHandler extends ChannelHandlerAdapter {

    /**
     * Creates a client-side handler.
     */
    public SubReqClientHandler() {
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) {
        for (int i = 0; i < 10; i++) {
            ctx.write(createRequest());
        }
        ctx.flush();
    }


    public static RequestMsgProto.Request createRequest(){
        RequestMsgProto.Request.Builder builder =RequestMsgProto.Request.newBuilder();
        builder.setRequestType(RequestMsgProto.Request.RequestType.SUCCESS);
        RequestMsgProto.Request.RequestData.Builder dataBuilder = RequestMsgProto.Request.RequestData.newBuilder();
        dataBuilder.setName("request");
        dataBuilder.setValue(112);
        builder.addData(dataBuilder);
        builder.addHttpCode(222);
        return builder.build();
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg)
            throws Exception {
        System.out.println("Receive server response : [" + msg + "]");
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        ctx.flush();
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        cause.printStackTrace();
        ctx.close();
    }
}
